library(dplyr)
library(readr)
library(tidyverse)
library(dplyr)
library(MASS)
library(ggplot2)
library(car)
library(tidyr)

#set wd
setwd("~/Downloads")

############################################################################################################################
##################### Issue Absorption and Candidate Valence in the 2020 and 2024 U.S. Presidential Elections ##############
############################################################################################################################

### Load the ANES 2020 Time Series dataset first
anes_2020 <- read_csv("anes_timeseries_2020_csv_20220210 2/anes_timeseries_2020_csv_20220210.csv")

############2020 DATASET########################
#rename V201033 to vote_choice_pres
anes_2020 <- anes_2020 %>% rename(vote_choice_pres = V201033) #DV pre-survey 
anes_2020 <- anes_2020 %>% rename(vote_choice_post = V202073) #DV post-survey 
anes_2020 <- anes_2020 %>% rename(biden_comp = V201210)
anes_2020 <- anes_2020 %>% rename(biden_honest = V201211)
anes_2020 <- anes_2020 %>% rename(trump_comp = V201214)
anes_2020 <- anes_2020 %>% rename(trump_honest = V201215)
anes_2020 <- anes_2020 %>% rename(pid = V201231x) #remove -9, -8, -1
anes_2020 <- anes_2020 %>% rename(ideology = V201200) #7pt scale, remove -9, -8, 99
anes_2020 <- anes_2020 %>% rename(immigration_ideology = V202232) #remove -5, -6, -7, -8, -9

# Recode vote choice: Biden=1, Trump=0 -- standard by research
#using post survey vote choice because 2024 "pre" equivalent only has ~150 responses
#2020
anes_2020 <- anes_2020 %>%
  mutate(vote_choice_binary = case_when(
    vote_choice_post == 1 ~ 1,   # Biden
    vote_choice_post == 2 ~ 0,   # Trump
    TRUE ~ NA_real_
  ))

#f2024--or post survey
# Recode DV: Harris = 1, Trump = 0
anes_2024 <- anes_2024 %>%
  mutate(vote_choice_binary_post = case_when(
    vote_choice_post == 1 ~ 1,   # Harris
    vote_choice_post == 2 ~ 0   # Trump
  ))

# Relative valence 
anes_2020$rel_comp <- anes_2020$biden_comp - anes_2020$trump_comp
anes_2020$rel_honest <- anes_2020$biden_honest - anes_2020$trump_honest

# Clean partisanship variable: Dem = 1, Ind = 2, Rep = 3 (simplify 7-point scale if needed)
anes_2020 <- anes_2020 %>%
  mutate(pid_simple = case_when(
    pid %in% c(1,2,3) ~ "Democrat",
    pid == 4 ~ "Independent",
    pid %in% c(5,6,7) ~ "Republican",
    TRUE ~ NA_character_
  )) %>%
  mutate(pid_simple = factor(pid_simple, levels = c("Independent", "Democrat", "Republican")))

# Immigration preference recode
anes_2024 <- anes_2024 %>%
  mutate(immig_pref = case_when(
    immigration_ideology %in% c(1, 2) ~ "Increase",   # liberal
    immigration_ideology == 3 ~ "Same",
    immigration_ideology %in% c(4, 5) ~ "Restrict",   # restrictionist
    TRUE ~ NA_character_
  )) %>%
  mutate(immig_pref = factor(immig_pref, levels = c("Same", "Increase", "Restrict")))

